package com.yuyou.fn.educational.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.wens.framework.service.impl.SuperServiceImpl;
import com.github.wens.mybatisplus.examples.Example;
import com.github.wens.mybatisplus.plugins.Page;
import com.google.common.base.Function;
import com.google.common.collect.Collections2;
import com.yuyou.fn.common.constant.JobNatureEnum;
import com.yuyou.fn.common.exception.BusException;
import com.yuyou.fn.common.rocketmq.Producer;
import com.yuyou.fn.common.util.*;
import com.yuyou.fn.educational.entity.AttendClassRecord;
import com.yuyou.fn.educational.entity.CourseClass;
import com.yuyou.fn.educational.entity.StudentRefund;
import com.yuyou.fn.educational.entity.StudentReg;
import com.yuyou.fn.educational.mapper.StudentRefundMapper;
import com.yuyou.fn.educational.service.*;
import com.yuyou.fn.educational.vo.*;
import com.yuyou.fn.platform.permission.DataPermission;
import com.yuyou.fn.settlement.service.ISettlementService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 *
 * StudentRefund 表数据服务层接口实现类
 *
 */
@Service
public class StudentRefundServiceImpl extends SuperServiceImpl<StudentRefundMapper, StudentRefund,Long> implements IStudentRefundService {

    private final static Logger log = LoggerFactory.getLogger(StudentRefundServiceImpl.class);

    @Resource
    private ICourseClassService courseClassService;

    @Resource
    private IStudentRegService studentRegService;

    @Resource
    private ISettlementService settlementService;

    @Resource
    private IClassLectureService classLectureService ;


    @Resource
    private IAttendClassRecordService attendClassRecordService;

    @Resource
    private Redisson redisson;

    @Resource
    private Producer producer;

    private static String[] totalTitles = new String[] { "合计","支付宝","微信","现金","余额","银行卡转账"} ;

    @Override
    public void deleteStudentRefund(Long studentRefundId) {
        StudentRefund studentRefund = findById(studentRefundId);
        if(studentRefund.getStatus() != 0 ){
            throw new BusException("不能删除");
        }
        deleteById(studentRefundId);
        studentRegService.changeRefundStatus(studentRefund.getStudentRegId() , 0 );
    }

    @Transactional
    @Override
    public StudentRefund saveStudentRefund(StudentRefundVo studentRefundVo, Principals.Principal principal) {
        RLock lock = redisson.getLock(String.format("regId:%s", studentRefundVo.getRegId()));
        if (lock.tryLock()) {
            try{
                StudentReg studentReg = studentRegService.findById(studentRefundVo.getRegId());
                if (studentReg.getRefundStatus() != null && studentReg.getRefundStatus() == 1) {
                    throw new BusException("前一笔退费正在处理中");
                }
                studentRegService.changeRefundStatus(studentRefundVo.getRegId(), 1);
                StudentRefund studentRefund = new StudentRefund();


                //临时控制17秋季班不能退费
                if (73 <= studentReg.getPeriodId() && studentReg.getPeriodId() <= 80) {
                    if (principal == null || principal.id.longValue() != 616522106544324608l) {
                        throw new BusException("16寒春暑秋、17寒春暑秋退费请在TMS处理");
                    }
                }

                BigDecimal refundAmount = studentReg.getRefundAmount();

                if (refundAmount == null) {
                    refundAmount = BigDecimal.ZERO;
                }

                if (BigDecimals.compare(studentRefundVo.getFinalRefundAmount(), studentReg.getPayAmount().subtract(refundAmount)) > 0) {
                    throw new BusException("退费金额不能大于应付金额");
                }


                if (studentRefundVo.getRefundLectureFrom() < studentReg.getStartAmount() || studentRefundVo.getRefundLectureFrom() > studentReg.getEndAmount()) {
                    throw new BusException("退费讲次超出报名讲次");
                }

                int regLectureAmount = studentReg.getEndAmount() - studentReg.getStartAmount() + 1;

                List<Integer> refundLectureNos = new ArrayList<>(regLectureAmount);
                for (int i = studentRefundVo.getRefundLectureFrom(); i <= studentReg.getEndAmount(); i++) {
                    refundLectureNos.add(i);
                }

                BeanUtils.copyProperties(studentRefund, studentRefundVo);

                CourseClass courseClass = courseClassService.findById(studentReg.getClassId(), "campusId", "campusName", "periodId", "periodName", "gradeId", "gradeName", "subjectId", "subjectName");

                studentRefund.setStudentRegId(studentReg.getRegId());
                studentRefund.setAreaTeamId(studentReg.getAreaTeamId());
                studentRefund.setBusTeamId(studentReg.getBusTeamId());
                studentRefund.setStudentId(studentReg.getStudentId());
                studentRefund.setStudentName(studentReg.getStudentName());
                studentRefund.setClassName(studentReg.getClassName());
                studentRefund.setStatus(0);

                studentRefund.setPayStatus(studentRefund.getRefundWay() == 3 ? 1 : 0);

                if(studentRefund.getPayStatus() ==1  ){
                    studentRefund.setPayTime(TimeUtils.now());
                }

                studentRefund.setApplyOperator(principal.name);
                studentRefund.setClassId(studentReg.getClassId());
                studentRefund.setClassName(studentReg.getClassName());
                studentRefund.setRefundLecture(StringUtils.join(refundLectureNos, ","));

                int refundLectureAmount = refundLectureNos.size();

                if (refundLectureAmount > regLectureAmount) {
                    throw new BusException("Illegal");
                }

                studentRefund.setAmount(studentRefundVo.getFinalRefundAmount());
                studentRefund.setRemainAmount(studentReg.getPayAmount().subtract(refundAmount).subtract(studentRefundVo.getFinalRefundAmount()));

                studentRefund.setPeriodId(courseClass.getPeriodId());
                studentRefund.setPeriodName(courseClass.getPeriodName());
                studentRefund.setCampusId(courseClass.getCampusId());
                studentRefund.setCampusName(courseClass.getCampusName());
                studentRefund.setGradeId(courseClass.getGradeId());
                studentRefund.setGradeName(courseClass.getGradeName());
                studentRefund.setSubjectId(courseClass.getSubjectId());
                studentRefund.setSubjectName(courseClass.getSubjectName());

                studentRefund.setCreateTime(TimeUtils.now());
                studentRefund.setUpdateTime(TimeUtils.now());
                insertSelective(studentRefund);

                //退账户默认自动审核
                if (studentRefund.getRefundWay() == 3) {
                    changeStatus(studentRefund.getStudentRefundId(), 1, "OK", principal);
                }
                return studentRefund;
            }finally {
                lock.unlock();
            }
        }
        return null;
    }


    @Override
    @Transactional
    public List<StudentRefund> saveStudentRefundList(List<StudentRefundVo> studentRefundVoList, Principals.Principal principal) {
        List<StudentRefund> studentRefundList=new ArrayList<>(studentRefundVoList.size());
        for (StudentRefundVo studentRefundVo:studentRefundVoList){
            studentRefundList.add(this.saveStudentRefund(studentRefundVo,principal));
        }
        return studentRefundList;
    }

    @Override
    public Page<StudentRefund> findStudentRefundList(StudentRefundQueryVo studentRefundQueryVo, DataPermission dataPermission, int pageNo, int pageSize) {
        if (studentRefundQueryVo.getEndAuditTime() != null) {
            studentRefundQueryVo.setEndAuditTime(TimeUtils.changeOneDateLastTime(studentRefundQueryVo.getEndAuditTime()));
        }
        if (studentRefundQueryVo.getEndPayTime() != null) {
            studentRefundQueryVo.setEndPayTime(TimeUtils.changeOneDateLastTime(studentRefundQueryVo.getEndPayTime()));
        }
        if (studentRefundQueryVo.getEndCreateTime() != null) {
            studentRefundQueryVo.setEndCreateTime(TimeUtils.changeOneDateLastTime(studentRefundQueryVo.getEndCreateTime()));
        }
        if (studentRefundQueryVo.getEndDate() != null) {
            studentRefundQueryVo.setEndDate(TimeUtils.changeOneDateLastTime(studentRefundQueryVo.getEndDate()));
        }
        Example<StudentRefund> studentRefundExample = StudentRefund.createExample();
        studentRefundExample.orderBy("status").orderBy("createTime").desc();

        Example.Criteria criteria = studentRefundExample.createCriteria();

        CriteriaUtils.fillCondition(criteria,studentRefundQueryVo);
        CriteriaUtils.fillConditionForBusPermission(criteria,dataPermission.getBusTeamIds());

        return findPageByExample(studentRefundExample,pageNo, pageSize );
    }

    @Override
    public Long countStudentRefund(StudentRefundQueryVo studentRefundQueryVo, DataPermission dataPermission) {
        Example<StudentRefund> studentRefundExample = StudentRefund.createExample();
        studentRefundExample.orderBy("createTime").desc();

        Example.Criteria criteria = studentRefundExample.createCriteria();

        CriteriaUtils.fillCondition(criteria,studentRefundQueryVo);
        CriteriaUtils.fillConditionForBusPermission(criteria,dataPermission.getBusTeamIds());

        return countByExample(studentRefundExample);
    }

    @Transactional
    @Override
    public void changeStatus(Long studentRefundId, Integer status, String result, Principals.Principal principal) {

        StudentRefund studentRefund = findById(studentRefundId);
        if(studentRefund.getRefundWay() != 3 && principal.name.equals(studentRefund.getApplyOperator())){
            throw new BusException("很抱歉，您无法审批自己发起的申请！");
        }
        StudentRefund update = new StudentRefund();
        update.setStudentRefundId(studentRefundId);
        update.setStatus(status);
        update.setReturnResult(result);
        update.setAuditOperator(principal.name);
        update.setUpdateTime(TimeUtils.now());
        update.setAuditTime(TimeUtils.now());
        boolean b = updateSelectiveById(update);
        if(b){
            if(status == 1 ){//审核通过
                afterAudit(studentRefund,principal);
            }else if(status==2){//审核未通过

                studentRegService.updateRefundStatus(studentRefund.getStudentRegId(),0);
            }
        }
    }

    private void afterAudit(StudentRefund studentRefund ,Principals.Principal principal) {
        final CourseClass courseClass = courseClassService.findById(studentRefund.getClassId());
        String[] lectureNos = studentRefund.getRefundLecture().split(",");





        List<Long> classLectureIds = classLectureService.lectureNo2ClassLectureId(courseClass.getClassId(),new ArrayList<>(Collections2.transform(Arrays.asList(lectureNos), new Function<String, Integer>() {
            @Override
            public Integer apply(String input) {
                return Integer.valueOf(input);
            }
        })));

        if( classLectureIds.size() != lectureNos.length ){
            throw new BusException("Ghosts");
        }



        if(studentRefund.getRefundWay() == 3){//退账户
            StudentRefund update = new StudentRefund();
            update.setStudentRefundId(studentRefund.getStudentRefundId());
            update.setPayStatus(1);
            updateSelectiveById(update);
        }

        final StudentReg studentReg = studentRegService.findById(studentRefund.getStudentRegId());

        boolean isAllLectureRefund = (studentReg.getEndAmount() - studentReg.getStartAmount() + 1 ) != lectureNos.length;

        classLectureService.deleteAttendanceRecordForStudent(studentReg.getRegId(),classLectureIds );
        settlementService.bookRefundForCourse( courseClass.getBusTeamId(), studentRefund.getStudentId() , courseClass.getClassName()  ,courseClass.getClassId() ,studentRefund.getAmount() , classLectureIds , studentRefund.getStudentRegId() , studentRefund.getStudentId() );

        if(isAllLectureRefund){
            studentReg.setStartAmount(studentReg.getStartAmount());
            studentReg.setEndAmount(studentReg.getEndAmount() - lectureNos.length );
        }else{
            //全退
            studentReg.setRegStatus(3);
            studentReg.setStartAmount(0);
            studentReg.setEndAmount(0);
            courseClassService.decreaseRegAmount(studentRefund.getClassId());
        }

        BigDecimal refundAmount = studentReg.getRefundAmount();

        if(refundAmount == null ){
            refundAmount = BigDecimal.ZERO ;
        }
        studentReg.setRefundAmount(refundAmount.add(studentRefund.getAmount()));
        studentReg.setRefundStatus(2);
        studentReg.setUpdateTime(TimeUtils.now());
        studentRegService.updateSelectiveById(studentReg);

        if(studentRefund.getRefundWay() != 3 ){
            settlementService.decreaseBalance(studentRefund.getStudentId(),studentRefund.getAmount(),"退费扣减");
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("regId",studentReg.getRegId());
        producer.send("student_refund_success_audit",null , JSONS.toBytes( jsonObject ) );

        Threads.delay(()->{
            //检查是否有差额消耗
            try{
                Example<AttendClassRecord> attendClassRecordExample = AttendClassRecord.createExample();
                attendClassRecordExample.createCriteria().andEqualTo("regId",studentReg.getRegId());
                List<AttendClassRecord> attendClassRecords = attendClassRecordService.findListByExample(attendClassRecordExample);
                boolean isAllConsume = true ;


                for(AttendClassRecord attendClassRecord : attendClassRecords ){
                    if(attendClassRecord.getFinanceFlag() == 0 ){
                        isAllConsume = false ;
                    }
                }

                if(isAllConsume){
                    List<Long> lectureIds = BeanUtils.toList(attendClassRecords,"classLectureId");
                    settlementService.checkDifferenceConsume(courseClass.getBusTeamId(),studentReg.getRegId(),courseClass.getClassId(),courseClass.getClassName(),studentReg.getStudentId(),lectureIds );
                }
            }catch (Exception e){
                log.error("处理差额消耗出错" , e );
            }


        },20);


    }




    /** 导出学生返款信息 */
    @Override
    public Workbook exportStudentRefund(StudentRefundQueryVo studentRefundQueryVo, DataPermission dataPermission) {

        Example<StudentRefund> studentRefundExample = StudentRefund.createExample();
        studentRefundExample.orderBy("createTime").desc();

        Example.Criteria criteria = studentRefundExample.createCriteria();

        CriteriaUtils.fillCondition(criteria,studentRefundQueryVo);
        CriteriaUtils.fillConditionForBusPermission(criteria,dataPermission.getBusTeamIds());

        List<StudentRefund> studentRefundList = findListByExample(studentRefundExample);
        List<Long> classIdList = BeanUtils.toList(studentRefundList, "classId");
        List<CourseClass> courseClassList=courseClassService.findByIds(classIdList);
        Map<Long, CourseClass> classMap = BeanUtils.toMap(courseClassList, "classId");
        SXSSFWorkbook studentRefundExcel = studentRefund2excel(studentRefundList,classMap);
        return studentRefundExcel;
    }


    public  SXSSFWorkbook studentRefund2excel(List<StudentRefund> studentRefundList,Map<Long, CourseClass> classMap) {

        SXSSFWorkbook excel = new SXSSFWorkbook();
        SXSSFSheet sheet = excel.createSheet("studentRefund");
        SXSSFRow firstRow = sheet.createRow(0);
        String[] titles = new String[] { "退费订单号" , "学生姓名" , "班级名称", "年级","科目","主讲教师","任教性质","期数", "退费讲次","退费金额", "退费原因", "退费详情","退费方式", "转账银行", "转账帐号", "开户城市", "开户人姓名", "申请时间","审批时间","审批状态","审核人","审批意见","支付时间", "支付状态","支付人" ,"报读校区" };

        SXSSFSheet totalsheet = excel.createSheet("总计");

        CellStyle cellStyle = excel.createCellStyle();
        DataFormat dataFormat = excel.createDataFormat();
        cellStyle.setDataFormat(dataFormat.getFormat("#,##0.00"));

        for (int i = 0; i < titles.length; i++) {
            firstRow.createCell(i).setCellValue(titles[i]);
        }
        for (int i = 0; i < studentRefundList.size(); i++) {
            SXSSFRow row = sheet.createRow(i + 1);
            StudentRefund studentRefund = studentRefundList.get(i);
            CourseClass courseClass=classMap.get(studentRefund.getClassId());
            int columnIndex = 0 ;
            SXSSFCell cell = row.createCell(columnIndex++);
            //cell.setCellType(CellType.STRING);
            cell.setCellValue(String.valueOf(studentRefund.getStudentRefundId()));

            cell = row.createCell(columnIndex++);
            cell.setCellValue(studentRefund.getStudentName());

            cell = row.createCell(columnIndex++);
            cell.setCellValue(studentRefund.getClassName());

            cell = row.createCell(columnIndex++);
            cell.setCellValue(StringUtils.defaultString(courseClass.getGradeName()));

            cell = row.createCell(columnIndex++);
            cell.setCellValue(StringUtils.defaultString(courseClass.getSubjectName()));

            cell = row.createCell(columnIndex++);
            cell.setCellValue(StringUtils.defaultString(courseClass.getTeacherName()));

            cell = row.createCell(columnIndex++);
            cell.setCellValue(EnumUtils.getName(JobNatureEnum.values() ,courseClass.getJobNature()));

            cell = row.createCell(columnIndex++);
            cell.setCellValue(studentRefund.getPeriodName());

            cell = row.createCell(columnIndex++);
            cell.setCellValue(studentRefund.getRefundLecture());

            cell = row.createCell(columnIndex++);
            cell.setCellType(CellType.NUMERIC);
            cell.setCellValue(studentRefund.getAmount()==null?0:studentRefund.getAmount().doubleValue());

            String description=studentRefund.getDescription()==null?"":studentRefund.getDescription();

            int split=description.indexOf(":");
            String refundReason=description;
            String reasonDetail="";
            if (split>=0){
                refundReason=description.substring(0,split);
                reasonDetail=description.substring(split+1,description.length());
            }

            cell = row.createCell(columnIndex++);
            cell.setCellValue(StringUtils.defaultString(refundReason));

            cell = row.createCell(columnIndex++);
            cell.setCellValue(StringUtils.defaultString(reasonDetail));


            cell = row.createCell(columnIndex++);
            cell.setCellValue(studentRefund.getRefundWay() == 0 ? "支付宝": (studentRefund.getRefundWay() == 1 ? "微信" :(studentRefund.getRefundWay() == 2 ?
                      "现金" : (studentRefund.getRefundWay() == 3 ?"虚拟余额账户" : ( studentRefund.getRefundWay() == 4 ? "银行卡转账" : "")))));

            cell = row.createCell(columnIndex++);
            cell.setCellValue(studentRefund.getBankName());

            cell = row.createCell(columnIndex++);
            cell.setCellValue(studentRefund.getCardNo());

            cell = row.createCell(columnIndex++);
            cell.setCellValue(studentRefund.getBankCity());

            cell = row.createCell(columnIndex++);
            cell.setCellValue(studentRefund.getCardUser());

            cell = row.createCell(columnIndex++);
            cell.setCellValue(studentRefund.getCreateTime() == null ? StringUtils.EMPTY : Utils.formatDate(studentRefund.getCreateTime(),"yyyy-MM-dd HH:mm:ss") );


            cell = row.createCell(columnIndex++);
            cell.setCellValue(studentRefund.getAuditTime() == null ? StringUtils.EMPTY : Utils.formatDate(studentRefund.getAuditTime(),"yyyy-MM-dd HH:mm:ss") );


            cell = row.createCell(columnIndex++);
            cell.setCellValue(studentRefund.getStatus() == 1 ? "审核通过" : (studentRefund.getStatus() == 2 ? "审核不通过" : "审核中"));

            cell = row.createCell(columnIndex++);
            cell.setCellValue(studentRefund.getAuditOperator());

            cell = row.createCell(columnIndex++);
            cell.setCellValue(StringUtils.defaultString(studentRefund.getReturnResult()));

            cell = row.createCell(columnIndex++);
            cell.setCellValue(studentRefund.getPayTime() == null ? StringUtils.EMPTY : Utils.formatDate(studentRefund.getPayTime(),"yyyy-MM-dd HH:mm:ss"));

            cell = row.createCell(columnIndex++);
            cell.setCellValue(studentRefund.getPayStatus() == 1 ? "已付款" : "未付款" );

            cell = row.createCell(columnIndex++);
            cell.setCellValue(studentRefund.getPayOperator());

            cell = row.createCell(columnIndex++);
            cell.setCellValue(studentRefund.getCampusName());


        }
        this.writeSummaryForReg(totalsheet,studentRefundList);
        return excel;
    }

    private void writeSummaryForReg(SXSSFSheet sheet, List<StudentRefund> studentRefundList) {

        SXSSFRow firstTotalRow = sheet.createRow(0);
        for (int i = 0; i < totalTitles.length; i++) {

            SXSSFCell cell = firstTotalRow.createCell(i);
            cell.setCellValue(totalTitles[i]);
        }
        int rowNum=1;
        int c=0;
        SXSSFRow row = sheet.createRow( rowNum);

        RefundWayAmount refundWayAmount=new RefundWayAmount();

        for (StudentRefund studentRefund:studentRefundList){
            refundWayAmount.setTotal(refundWayAmount.getTotal().add(studentRefund.getAmount()));
            switch(studentRefund.getRefundWay()) {
                case 0:
                    refundWayAmount.setAlipay(refundWayAmount.getAlipay().add(studentRefund.getAmount()));
                    break;
                case 1:

                    refundWayAmount.setWeChat(refundWayAmount.getWeChat().add(studentRefund.getAmount()));
                    break;
                case 2:

                    refundWayAmount.setCash(refundWayAmount.getCash().add(studentRefund.getAmount()));
                    break;
                case 3:
                    refundWayAmount.setBalance(refundWayAmount.getBalance().add(studentRefund.getAmount()));
                    break;
                case 4:
                    refundWayAmount.setBankCard(refundWayAmount.getBankCard().add(studentRefund.getAmount()));
                    break;
            }

        }

 /*退款方式：0-支付宝，1-微信，2-现金，3-虚拟余额账户 ，4-银行卡转账*/
        SXSSFCell cell = row.createCell(c++);
        cell.setCellValue(BigDecimals.formatBigDecimal(refundWayAmount.getTotal(),"0.00"));

        cell = row.createCell(c++);
        cell.setCellValue(BigDecimals.formatBigDecimal(refundWayAmount.getAlipay(),"0.00"));

        cell = row.createCell(c++);
        cell.setCellValue(BigDecimals.formatBigDecimal(refundWayAmount.getWeChat(),"0.00"));

        cell = row.createCell(c++);
        cell.setCellValue(BigDecimals.formatBigDecimal(refundWayAmount.getCash(),"0.00"));

        cell = row.createCell(c++);
        cell.setCellValue(BigDecimals.formatBigDecimal(refundWayAmount.getBalance(),"0.00"));

        cell = row.createCell(c++);
        cell.setCellValue(BigDecimals.formatBigDecimal(refundWayAmount.getBankCard(),"0.00"));
    }

    @Override
    public void changeStudentPayStatus(Long studentRefundId, String operator) {
        StudentRefund studentRefund = findById(studentRefundId);
        if(studentRefund.getStatus() != 1 ){//没有审核通过
            throw new BusException("非法操作");
        }
        StudentRefund update = new StudentRefund();
        update.setStudentRefundId(studentRefundId);
        update.setPayStatus(1);
        update.setPayTime(TimeUtils.now());
        update.setPayOperator(operator);
        updateSelectiveById(update);
    }

    @Override
    public List<StudentRefund> findListByQueryVo(StudentRefundQueryVo studentRefundQueryVo, List<Long> busTeamIds,List<Long> periodIds, int descByCreate) {
        Example<StudentRefund> studentRefundExample = StudentRefund.createExample();
        if (descByCreate==1){
            studentRefundExample.orderBy("createTime").desc();
        }else {
            studentRefundExample.orderBy("createTime");
        }


        Example.Criteria criteria = studentRefundExample.createCriteria();

        CriteriaUtils.fillCondition(criteria,studentRefundQueryVo);
        CriteriaUtils.fillConditionForBusPermission(criteria,busTeamIds);
        if (periodIds!=null && periodIds.size()>0){
            criteria.andIn("periodId",periodIds);
        }
        criteria.andIsNotNull("auditTime");
        return this.findListByExample(studentRefundExample);
    }

    @Override
    public List<PeriodBusTeamGradeRefundAmountVo> findPeriodBusTeamGradeRefundAmount(StudentRefundQueryVo studentRefundQueryVo) {
        return this.autoMapper.findPeriodBusTeamGradeRefundAmount(studentRefundQueryVo);
    }

    @Override
    public SumRefundVo findSumRefund(StudentRefundQueryVo studentRefundQueryVo) {
        return this.autoMapper.sumRefund(studentRefundQueryVo);
    }

    @Override
    public List<StudentRefund> findStudentRefundByClassIdStatus(long classId, int status) {
        Example<StudentRefund> studentRefundExample = StudentRefund.createExample();
        studentRefundExample.orderBy("createTime").desc();

        Example.Criteria criteria = studentRefundExample.createCriteria();
        criteria.andEqualTo("classId",classId).andEqualTo("status",status);
        return  this.findListByExample(studentRefundExample);
    }

    @Override
    public List<StudentRefund> findToBalanceRefundByStudentIds(List<Long> studentIds,String ...columns) {
        if (Utils.checkListEmpty(studentIds)){
            return Collections.EMPTY_LIST;
        }
        Example<StudentRefund> studentRefundExample = StudentRefund.createExample();

        Example.Criteria criteria = studentRefundExample.createCriteria();
        criteria.andIn("studentId",studentIds).andEqualTo("refundWay",3);
        if (columns!=null){
            studentRefundExample.selectProperties(columns);
        }
        return  this.findListByExample(studentRefundExample);
    }
}